package task3.tracking;

public class TypeConverter {

	public static long toLong(byte[] data) {
		if (data == null || data.length != 8) return 0x0;
		// ----------
		return (long)(
		// (Below) convert to longs before shift because digits
		// are lost with ints beyond the 32-bit limit
		(long)(0xff & data[0]) << 56 |
		(long)(0xff & data[1]) << 48 |
		(long)(0xff & data[2]) << 40 |
		(long)(0xff & data[3]) << 32 |
		(long)(0xff & data[4]) << 24 |
		(long)(0xff & data[5]) << 16 |
		(long)(0xff & data[6]) << 8 |
		(long)(0xff & data[7]) << 0
		);
		}
		public static long[] toLongA(byte[] data) {
		if (data == null || data.length % 8 != 0) return null;
		// ----------
		long[] lngs = new long[data.length / 8];
		for (int i = 0; i < lngs.length; i++) {
		lngs[i] = toLong( new byte[] {
		data[(i*8)],
		data[(i*8)+1],
		data[(i*8)+2],
		data[(i*8)+3],
		data[(i*8)+4],
		data[(i*8)+5],
		data[(i*8)+6],
		data[(i*8)+7],
		} );
		}
		return lngs;
		}
		
		public static double toDouble(byte[] data) {
			if (data == null || data.length != 8) return 0x0;
			// ---------- simple:
			return Double.longBitsToDouble(toLong(data));
			}
			
			public static double[] toDoubleA(byte[] data) {
			if (data == null) return null;
			// ----------
			if (data.length % 8 != 0) return null;
			double[] dbls = new double[data.length / 8];
			for (int i = 0; i < dbls.length; i++) {
			dbls[i] = toDouble( new byte[] {
			data[(i*8)],
			data[(i*8)+1],
			data[(i*8)+2],
			data[(i*8)+3],
			data[(i*8)+4],
			data[(i*8)+5],
			data[(i*8)+6],
			data[(i*8)+7],
			} );
			}
			return dbls;
			}

	public static byte[] toByta(long data) {

	return new byte[] {
	(byte)((data >> 56) & 0xff),
	(byte)((data >> 48) & 0xff),
	(byte)((data >> 40) & 0xff),
	(byte)((data >> 32) & 0xff),
	(byte)((data >> 24) & 0xff),
	(byte)((data >> 16) & 0xff),
	(byte)((data >> 8) & 0xff),
	(byte)((data >> 0) & 0xff),
	};
	}
	/**
	 * Function that convert double data to array of bytes
	 * @param data double type data to be converted 
	 * @return byte representation of double data
	 */
	public static byte[] toByta(double data){
		
		long longBits = Double.doubleToRawLongBits(data);
//		System.out.println( doubleToRawLongBits);
		return toByta(longBits);		
	}
	
	
	public static byte[] toByta(double[] data) {
	if (data == null) return null;
	// ----------
	byte[] byts = new byte[data.length * 8];
	for (int i = 0; i < data.length; i++)
	System.arraycopy(toByta(data[i]), 0, byts, i * 8, 8);
	return byts;
	}
	
	private static byte[] toBytaInt(int data){
		return new byte[]{
				(byte) ((data >> 24) & 0xff),
				(byte) ((data >> 16) & 0xff),
				(byte) ((data >> 8) & 0xff),
				(byte) ((data >> 0) & 0xff),
		};
	}
	
}
